from django.contrib.auth.models import User
from django.core.validators import RegexValidator
from django.http import HttpResponse
from django.shortcuts import render
from utils.tencent.sms import send_sms_single
from django.conf import settings
from django import forms
from app01 import models
import random


def send_sms(request):
    '''
        发送短信
        template_id: 腾讯云短信模板ID,登录和注册的模板id不同
        实现：?tpl=login template_id->2058855
             ?tpl=register template_id->2058856
    '''
    tpl = request.GET.get('tpl')
    code = random.randrange(1000, 9999)
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    # not与逻辑判断句if连用，代表not后面的表达式为False的时候，执行冒号后面的语句
    # 双重否定表肯定
    if not template_id:
        return HttpResponse('模板不存在')
    res = send_sms_single('15835484769', template_id, [code, ])
    # print(res)
    if res['result'] == 0:
        return HttpResponse('成功')
    else:
        return HttpResponse(res['errmsg'])


class RegisterModelForm(forms.ModelForm):
    # 增加正则表达式校验
    mobile_phone = forms.CharField(label='手机号',
                                   validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}))

    confirm_password = forms.CharField(
        label='重复密码',
        # 给此标签限制type类型，并添加属性的简便写法
        widget=forms.PasswordInput())

    code = forms.CharField(
        label='验证码',
        widget=forms.TextInput())

    # 通过一个内嵌类 "class Meta" 给你的 model 定义元数据选项 (meta options)
    class Meta:
        # 与models建立了依赖关系
        model = models.UserInfo
        # 字段
        # fields = '__all__' 默认的models中的顺序
        # 可用fields指定顺序
        fields = ['username','email','password','confirm_password','mobile_phone', 'code']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # self.fields可以拿到以上的每一个字段
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = f'请输入{field.label}'


def register(request):
    # 实例化
    form = RegisterModelForm()
    return render(request, 'register.html', {'form': form})
